import math
import mat


def tf(doc):
    '''
    doc: count of each iterm in the document
    return tf
    '''
    dl = sum(doc)
    return [ic / dl for ic in doc]


def idf(term):
    '''
    iterm: count of the iterm in each document
    return smooth idf
    '''
    return 1 + math.log((1 + len(term)) / (1 + sum(map(bool, term))))


def tfidf(bow):
    '''
    bow: a matrix of term count
    return tfidf matrix
    '''
    tf_mat = [tf(doc) for doc in bow]
    idfs = [idf(list(term)) for term in mat.cols(bow)]
    res = [[a * b for a, b in zip(tfs, idfs)] for tfs in tf_mat]
    return res
